package com.qf.mvc01.controller;


import com.qf.mvc01.entity.UserLogin;
import com.qf.mvc01.utils.MyCache;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginCaptchaController {

    @PostMapping("/lookcode")
    public void login( String ucode, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //0.设置编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //1.拿到session中存在的captcha验证码
        String captcha = (String) session.getAttribute("captcha");
        //2.获取用户填写的验证码，并且将session和用户填写的验证码都变成小写形势以便于忽略验证码大小写问题
        ucode = ucode.toLowerCase();
        captcha = captcha.toLowerCase();
        //3.进行验证码比较，如果验证码通过那么就比较当前用户的姓名是否存在
        if(ucode.equals(captcha)){
            response.getWriter().print("验证码输入正确！");
        }else {
            response.getWriter().print("验证码输入有误！");
        }
    }

    @PostMapping("/lookuser")
    public void login(String uname, String upassword, String uphone, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //0.设置编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        if(uname.equals("")||uname==null){
            response.getWriter().print("用户名不能为空");
        }else {
            //4.进行用户姓名的比较与缓存类中的数据,这里的key是uname
            UserLogin user = (UserLogin) MyCache.cache.get(uname);
            if (user != null) {
                response.getWriter().print("该用户已存在,不允许重复注册！");
            } else {
                MyCache.cache.put(uname, new UserLogin(uname, upassword, uphone));
                response.getWriter().print("用户名申请通过！");
            }
        }
    }
}
